package com.heue.voice;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.heue.voice.adapter.TaskListAdapter;
import com.heue.voice.bean.TaskListBean;
import com.heue.voice.extend.FileSelecter;
import com.heue.voice.util.HandlerUtil;
import com.heue.voice.util.JsonCfg;
import com.heue.voice.util.MediaUtil;
import com.heue.voice.util.RunUtil;
import com.heue.voice.util.TaskQueue;
import com.heue.voice.util.TimeUtil;

import java.io.File;
import java.net.FileNameMap;
import java.net.URLConnection;

public class MainActivity extends FileSelecter {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private Activity context;
    private TaskQueue taskQueue;
    private void init() {
        //初始化常量
        context = this;
        //检查是否第一次启动
        RunUtil.isFirstRun(context);
        //检查权限
        //RunUtil.permissionCheck(this);
        //绑定控件
        ListView listView = findViewById(R.id.list_taskList);
        Button btn = findViewById(R.id.btn_add);
        //绑定监听者
        View.OnClickListener onClickListener = v -> addTask();
        btn.setOnClickListener(onClickListener);
        //初始化变量
        taskQueue = new TaskQueue("first");
        taskQueue.startLoopQueue();
        //绑定常量
        AdapterView.OnItemClickListener onItemClickListener = (parent, view, position, id) -> {
            //弹出窗口，播放文件
            TaskListBean taskListBean = adapter.getItem(position);
            String path = taskListBean.getFilePath();
            if(path == null) {
                showToast("该文件还未准备好");
                return;
            }
            File file = new File(path);
            if(!file.exists()) {
                showToast("文件已被删除");
                return;
            }
            if(mediaUtil == null) {
                mediaUtil = new MediaUtil(context);
            }
            if(mediaUtil.isShowing())
                return;
            //handler.sendMessage(handler.obtainMessage(5, path));
            handler.post(() -> {
                mediaUtil.setContent("正在播放音频...\n\n返回可停止播放");
                mediaUtil.play(path);
                mediaUtil.show();
            });
        };
        /*
        AdapterView.OnItemLongClickListener onItemLongClickListener = (parent, view, position, id) -> {
            onLongClickItem();
            return true;
        };*/
        listView.setOnItemClickListener(onItemClickListener);
        //为分享、重构、删除做准备
        // listView.setOnItemLongClickListener(onItemLongClickListener);
        initListData(listView);

    }

    private void onLongClickItem() {
        dialog = new Dialog(this);
        @SuppressLint("InflateParams") View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_menu, null);
        dialog.setContentView(contentView);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
    }

    private Dialog dialog;
    private MediaUtil mediaUtil;
    private void addTask() {
        if (dialog == null) {
            dialog = new Dialog(context, R.style.MainDialogStyle);
            dialog.setContentView(R.layout.dialog_add);
            dialog.setTitle("添加任务");
            EditText edt_file = dialog.findViewById(R.id.dialog_edt_filePath);
            EditText edt_save = dialog.findViewById(R.id.dialog_edt_savePath);
            Button btn_choose = dialog.findViewById(R.id.dialog_btn_chooseFile);
            Button btn_default = dialog.findViewById(R.id.dialog_btn_defaultPath);
            Button btn_start = dialog.findViewById(R.id.dialog_btn_sure);
            edt_save.setText(getSavePath());
            @SuppressLint("NonConstantResourceId") View.OnClickListener onClickListener = v -> {
                switch (v.getId()) {
                    case R.id.dialog_btn_chooseFile:
                        showFileChooser();
                        break;
                    case R.id.dialog_btn_defaultPath:
                        edt_save.setText(getString(R.string.des_defaultDir));
                        break;
                    case R.id.dialog_btn_sure:
                        String file = edt_file.getText().toString();
                        String path = edt_save.getText().toString();
                        if (file.length() != 0 && path.length() != 0) {
                            if (!file.startsWith("/") || !path.startsWith("/")) {
                                showToast("只支持路径");
                            } else {
                                FileNameMap fileNameMap = URLConnection.getFileNameMap();
                                String type = fileNameMap.getContentTypeFor(file);
                                if(!type.startsWith("video")) {
                                    showToast("不是视频");
                                    return;
                                }
                                //添加任务
                                taskStart(file, path);
                                dialog.dismiss();
                                dialog = null;
                            }
                        } else {
                            showToast("请勿留空");
                        }
                        break;
                }
            };

            btn_choose.setOnClickListener(onClickListener);
            btn_default.setOnClickListener(onClickListener);
            btn_start.setOnClickListener(onClickListener);

            FileSelecter.ResultListener r = edt_file::setText;
            this.setListener(r);
        }
        dialog.show();
    }

    private void taskStart(final String filePath, final String savePath) {
        Runnable runnable = () -> {
            String file, save;
            file = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.lastIndexOf("."));//文件名称
            TaskListBean taskListBean = new TaskListBean(file, TimeUtil.formatData(System.currentTimeMillis()), 0);
            if (!savePath.endsWith("/")) {
                save = savePath + "/";
            } else
                save = savePath;
            //保存文件的绝对路径
            save = save + (file + ".aac");
            //保存文件路径
            String resultFilePath = save;
            int position = adapter.getCount();
            HandlerUtil.HandlerProgressListener handlerProgressListener = new HandlerUtil.HandlerProgressListener() {
                @Override
                public void onStart(int max) {
                    //progressWhere = new int[]{position, max};
                    //handler.sendEmptyMessage(1);
                    handler.post(() -> {
                        //改变进度条最大值
                        adapter.getProgressBar(position).setMax(max);
                    });
                }

                @Override
                public void onProgress(int progress) {
                    //progressWhere = new int[]{position, progress};
                    //handler.sendEmptyMessage(2);
                    handler.post(() -> {
                        //进度条进度改变
                        adapter.getProgressBar(position).setProgress(progress);
                    });
                }

                @Override
                public void onFinish() {
                    //触发保存列表内容
                    //progressWhere = new int[]{position, 0};
                    //handler.sendEmptyMessage(4);
                    handler.post(() -> adapter.finishProgress(jsonCfg, resultFilePath, position));
                }
            };
            HandlerUtil h = new HandlerUtil(handlerProgressListener);
            JsonCfg cfg = new JsonCfg(context);
            cfg.writeCfg("savePath", savePath); //保存当前的文件储存路径
            //handler.sendMessage(handler.obtainMessage(3, taskListBean));
            //添加列表项
            handler.post(() -> adapter.addItem(taskListBean));
            h.initMediaDecode(filePath, savePath, save);
        };
        if(!RunUtil.permissionCheck(context)) {
            //无权限
            taskQueue.stopLoopQueue();
        } else {
            taskQueue.startLoopQueue();
        }
        taskQueue.addTask(runnable);
    }

    private static TaskListAdapter adapter;
    private void initListData(ListView lsv) {
        //读取列表信息
        jsonCfg = new JsonCfg(context, "/list.cfg");
        adapter = new TaskListAdapter(context, jsonCfg.readListCfg());
        lsv.setAdapter(adapter);
        /*TaskListBean taskListBean;
        JsonCfg jsonCfg = new JsonCfg(context, "/list.cfg");
        for(int i= 1; i < 20;i++) {
            taskListBean = new TaskListBean("第几个文件" + i, "文件的信息" + i);
            jsonCfg.writeListCfg(taskListBean);
        }*/
    }

    //打开资源管理器
    public void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(Intent.createChooser(intent, "选择视频文件"), 2);
    }

    //配置文件
    private String getSavePath() {
        JsonCfg cfg = new JsonCfg(context);
        String s = cfg.readCfg();
        if (s.isEmpty()) {
            return getString(R.string.des_defaultDir);
        } else {
            return s;
        }
    }
    //

    private void showToast(String string) {
        Toast.makeText(context, string, Toast.LENGTH_SHORT).show();
    }

    //private static int[] progressWhere;
    //private String resultFilePath;
    private static  JsonCfg jsonCfg;
    private final Handler handler = new Handler(Looper.myLooper());
    /*@SuppressLint("HandlerLeak")
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    //改变进度条最大值
                    adapter.getProgressBar(progressWhere[0]).setMax(progressWhere[1]);
                    break;
                case 2:
                    //进度条进度改变
                    adapter.getProgressBar(progressWhere[0]).setProgress(progressWhere[1]);
                    break;
                case 3:
                    //添加列表项
                    adapter.add((TaskListBean) msg.obj);
                    break;
                case 4:
                    adapter.finishProgress(jsonCfg, resultFilePath, progressWhere[0]);
                    break;
                case 5:
                    mediaUtil.setContent("正在播放音频...\n\n返回可停止播放");
                    mediaUtil.play((String) msg.obj);
                    mediaUtil.show();
                    break;
            }
        }
    };*/

    //退出
    static boolean Exit;
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!Exit) {
                Exit = true;
                showToast("再返回一次退出");
                new Thread(() -> {
                    try {
                        Thread.sleep(1000);
                        Exit = false;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }).start();
            } else {
                RunUtil.stopApp(context);
            }
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }

}